<template>
  <div class="app-container">
    <div v-if="userInfo">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card>
            <el-tabs v-model="activeTab" @tab-click="togo" :lazy="true">
              <el-tab-pane label="个人信息" name="userCard">
                <user-card v-if="activeTab == 'userCard'" @refreshInfo="getUserInfo" :userInfo.sync="userInfo"
                  :categories="categories" />
              </el-tab-pane>
              <el-tab-pane label="安全中心" name="accountSafe">
                <account-safe v-if="activeTab == 'accountSafe'" @refreshInfo="getUserInfo" :userInfo.sync="userInfo"
                  ref="accountSafeRef"></account-safe>
              </el-tab-pane>
              <el-tab-pane label="个人预约" name="myBook">
                <my-book v-if="activeTab == 'myBook'" @getOrdersInfo="openPayDialog" ref="myBookRef"></my-book>
              </el-tab-pane>
              <el-tab-pane label="个人租借" name="myRent">
                <my-rent v-if="activeTab == 'myRent'" @getOrdersInfo="openPayDialog" ref="myRentRef"></my-rent>
              </el-tab-pane>
              <el-tab-pane label="个人订单" name="myOrder">
                <my-orders v-if="activeTab == 'myOrder'" @getOrdersInfo="openPayDialog" ref="myOrdersRef"></my-orders>
              </el-tab-pane>
              <el-tab-pane label="问题反馈" name="help">
                <help v-if="activeTab == 'help'" ref="helpRef"></help>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </el-col>

      </el-row>
    </div>

    <my-dialog ref="payDialogRef" :title="payDialog.title" :width="payDialog.width" :height="payDialog.height"
      :visible="payDialog.visible" @onClose="onPayClose" @onConfirm="onPayConfirm">
      <div slot="content">
        <el-result v-if="userInfo.balance < ordersInfo.ordersCost" icon="warning" title="余额不足">
          <template slot="extra">
            <router-link :to="'/account/accountSafe'">
              <el-link type="primary">前往充值</el-link>
            </router-link>
          </template>
        </el-result>
        <div v-else>
          <h1 v-if="!ordersOutTime" style="color:red;text-align:center;">¥ {{ ordersInfo.ordersCost }}</h1>
          <h1 v-if="ordersOutTime" style="color:red;text-align:center;">¥ {{ returnOrderCost().cost }}</h1>
          <!-- @finish="autoPayClose" -->
          <el-statistic v-if="ordersStopCountDown != null" class="tiptext" ref="statistic" format="m:ss" prefix="请在"
            suffix="时间内完成订单支付" :value="ordersStopCountDown" time-indices />
          <p v-else class="tiptext">请支付超时费用</p>
          <my-valid-input :type="true" @giveInputValue="getPayInputValue" ref="payInputRef"></my-valid-input>
          <el-row v-if="payCount >= 3" style="margin-top:20px">
            <el-col :span="7" :offset="6">
              <el-input v-model="payCode" placeholder="输入正确结果" clearable />
            </el-col>
            <el-col :span="5" :offset="1">
              <el-image :src="codeImage" @click="getMathCodeImage" class="codeImg"></el-image>
            </el-col>
          </el-row>
        </div>
      </div>
    </my-dialog>
  </div>
</template>

<script>
import { getUserAllInfo } from "@/api/user";
import { getCategoryApi } from "@/api/category";
import { getMathCodeImageApi, checkMathCodeApi } from "@/api/captcha";
import { finishPayApi } from "@/api/orders";
import { checkAssetKeyApi } from "@/api/asset"

import userCard from './components/UserCard'
import accountSafe from './components/AccountSafe'
import myBook from './components/MyBook'
import myRent from './components/MyRent'
import myOrders from './components/MyOrders'
import help from './components/Help'
import myDialog from "@/components/MyDialog/index";
import myValidInput from '@/components/MyValidInput';
export default {
  name: 'AccountCenter',
  components: { userCard, accountSafe, myBook, myRent, myOrders, myDialog, myValidInput, help },
  data() {
    return {
      activeTab: '',
      userInfo: '',
      //运动类别
      categories: "",
      //子组件传递的订单信息
      ordersInfo: '',
      //支付弹框
      payDialog: {
        title: "支付订单",
        width: 500,
        height: 120,
        visible: false,
      },
      //订单倒计时
      ordersStopCountDown: '',
      //支付密码输入框
      payInput: "",
      //错误支付次数
      payCount: 0,
      //验证码
      codeImage: "",
      //验证码输入
      payCode: "",

      //区分是否超时订单
      ordersOutTime: undefined,
    }
  },
  created() {
    this.getCategory();
    this.activeTab = this.$route.name
  },
  methods: {
    //点击加载对应的模块
    togo(tab) {
      this.$store.dispatch('tagsView/delView', this.$route).then(() => {
        this.$router.replace({ path: `/account/${tab.name}` });
      })
    },
    //获取用户信息
    async getUserInfo() {
      let res = await getUserAllInfo({ id: this.$store.getters.userId });
      let copydata = res.data;
      if (res.data.user.hobbies != null) {
        //取现有全部类型
        let categoryIds = [];
        this.categories.forEach(item => {
          categoryIds.push(item.id);
        })
        //用户现有类型
        let userHobbyIds = copydata.user.hobbies.split(",").map(Number);
        //全部类型与用户现有类型取交集，检查是否有类型失效
        copydata.user.hobbies = categoryIds.filter(item => {
          return userHobbyIds.includes(item);
        })
      }
      copydata.hobbiyName = this.getHobbiyName(copydata.user.hobbies)
      this.userInfo = copydata;
    },
    //获取运动类型
    async getCategory() {
      let res = await getCategoryApi();
      if (res && res.code == 200) {
        this.categories = res.data;
        if (this.categories != null) {
          this.getUserInfo();
        }
      }
    },
    //获取兴趣爱好标签
    getHobbiyName(array) {
      let list = [];
      if (array != null) {
        this.categories.forEach(item => {
          array.forEach(index => {
            if (index == item.id) {
              list.push(item.label)
            }
          })
        });
      }
      return list;
    },
    //支付刷新
    payRefresh() {
      switch (this.activeTab) {
        case 'userCard':
          break;
        case 'accountSafe':
          break;
        case 'myBook':
          this.$refs.myBookRef.cancelRowColor();
          this.$refs.myBookRef.getAllFieldBook();
          break;
        case 'myRent':
          this.$refs.myRentRef.cancelRowColor();
          this.$refs.myRentRef.getAllEquipmentRent();
          break;
        case 'myOrder':
          this.$refs.myOrdersRef.cancelRowColor();
          this.$refs.myOrdersRef.getUserOrders();
          break;
        case 'help':
          break;
        default:
          break;
      }
    },

    //打开支付弹框
    openPayDialog(val) {
      this.ordersInfo = val;

      let nowTime = new Date().getTime();

      //超时订单计算
      let outTime = nowTime - (new Date(this.ordersInfo.backTime)).getTime() + 1000 * 60 * 10;
      if (outTime <= 0) {
        this.ordersOutTime = false;
      } else if (outTime > 0) {
        this.ordersOutTime = true;
      }


      if (!this.ordersOutTime) {
        let ordersTime = (new Date(this.ordersInfo.ordersTime)).getTime() + 1000 * 60 * 10;
        if (nowTime < ordersTime) {
          this.ordersStopCountDown = ordersTime;
          this.$refs.payDialogRef.canConfirm = true;
          this.payDialog.visible = true;
          this.payTimeOut = setTimeout(() => {
            this.autoPayClose();
          }, ordersTime - nowTime);
        } else {
          this.$message.error("订单已超时,支付失败");
          this.payRefresh();
        }
      } else {
        //租赁超时订单
        this.payDialog.visible = true;
        this.ordersStopCountDown = null;
      }

    },
    //密码框值
    getPayInputValue(value) {
      this.payInput = value;
    },
    //获取四则运算验证码
    async getMathCodeImage() {
      this.codeImage = await getMathCodeImageApi();
    },
    //自动关闭支付弹框
    autoPayClose() {
      if (this.payDialog.visible) {
        this.payDialog.visible = false;
        this.$message.info("支付超时已自动取消订单");
        this.payRefresh();
        this.$refs.payInputRef.cleanInput();
      }
    },
    //关闭支付弹框
    onPayClose() {
      clearTimeout(this.payTimeOut);
      this.payDialog.visible = false;
      this.payRefresh();
      this.$refs.payInputRef.cleanInput();
    },
    //提交支付信息
    onPayConfirm() {
      if (this.payCount < 3) {
        this.checkAssetPayKey();
      } else {
        this.checkMathCode();
      }
      if (this.payCount == 2) {
        this.getMathCodeImage();
      }
    },
    //发起校验密码
    async checkAssetPayKey() {
      let res = await checkAssetKeyApi({ id: this.userInfo.user.assetId, assetKey: this.payInput }).catch(() => {
        this.$refs.payInputRef.cleanInput();
        this.payCode = '';
        this.payCount++
      });
      if (res && res.code == 200) {
        clearTimeout(this.payTimeOut);
        this.finishPay();
        this.payDialog.visible = false;
      }
    },
    //输错三次密码，验证码
    async checkMathCode() {
      let res = await checkMathCodeApi({ mathCode: this.payCode }).catch(() => {
        this.payCode = '';
      }).finally(this.getMathCodeImage())
      if (res && res.code == 200) {
        this.checkAssetPayKey();
      }
    },
    //完成支付
    async finishPay() {
      let parm;
      if (this.ordersOutTime) {
        //超时
        parm = this.returnOrderCost();
      } else {
        //未超时
        parm = {
          id: this.ordersInfo.oid,
          no: this.ordersInfo.no,
          cost: this.ordersInfo.ordersCost,
          point: this.ordersInfo.point,
          type: this.ordersInfo.type,
          status: this.ordersInfo.ordersStatus,
          version: this.ordersInfo.ordersVersion,
          uid: this.ordersInfo.uid
        }
      }
      let res = await finishPayApi(parm);
      if (res && res.code == 200) {
        this.$message.success(res.msg)
        this.payRefresh();
      }
      this.$refs.payInputRef.cleanInput();
      clearTimeout(this.payTimeOut);
    },
    //返回超时订单信息
    returnOrderCost() {
      let outTime = new Date().getTime() - (new Date(this.ordersInfo.backTime)).getTime() + 1000 * 60 * 10;
      //这里的outTime一定要大于0
      let count = Math.ceil(outTime / (1000 * 60 * 60))
      let outCost = count * this.ordersInfo.rentCost;
      let parm = {
        uid: this.$store.getters.userId,
        no: this.ordersInfo.oid,
        cost: 0,
        type: 3
      }
      //若超时费用大于器材单价，则按单价支付，器材归用户所有
      if (this.ordersInfo.buyCost != null && this.ordersInfo.buyCost > 0 && outCost >= this.ordersInfo.buyCost) {
        parm.cost = this.ordersInfo.buyCost;
      } else {
        parm.cost = outCost;
      }
      return parm;
    },
  },
  watch: {
    payInput(val) {
      if (val.length >= 6) {
        this.$refs.payDialogRef.canConfirm = false;
      } else {
        this.$refs.payDialogRef.canConfirm = true;
      }
    }
  },
}
</script>
<style lang="scss" scoped>
.tiptext {
  text-align: center;
  margin-bottom: 20px;
  font-size: 14px;
  color: #606266;
}

.codeImg {
  width: 100%;
  height: 36px;
  padding: 5px 0;
  border: 1px solid #ddd;
}
</style>
